package user.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import core.constants.Constant;
import core.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import user.domain.User;
import user.domain.user.vo.UserDetailVO;
import user.mapper.CUserMapper;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManage {
    @Autowired
    private RedisService redisService;

    @Autowired
    private CUserMapper userMapper;

    public UserDetailVO getUserById(Long userId) {
        String userKey = getUserKey(userId);
        UserDetailVO userDetailVO;
        if(redisService.hasKey(userKey)){
            userDetailVO = redisService.getCacheObject(userKey, UserDetailVO.class);
            if(userDetailVO != null){
                redisService.expire(userKey, Constant.USER_EXP, TimeUnit.SECONDS);
                return userDetailVO;
            }
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserId, userId));
        if(user == null){
            return null;
        }
        refreshUserCache(user);
        userDetailVO = BeanUtil.copyProperties(user, UserDetailVO.class);
        return userDetailVO;
    }

    public void refreshUserCache(User user) {
        redisService.setCacheObject(getUserKey(user.getUserId()), user,
                Constant.USER_EXP, TimeUnit.MINUTES);
    }

    private String getUserKey(Long userId){
        return Constant.USER_CACHE + userId;
    }
}
